<template>
  <div @click="hideEmoji" class="moment-publish">
    <div style="display: flex;justify-content: space-between;align-items: center;height: 35px;padding: 0 10px;">
      <i class="el-icon-arrow-left" style="font-size: 18px;color: #434343;cursor: pointer" @click="navigate('/home/moment/main')"></i>
      <el-button type="success" size="mini" style="display: inline;float: right" @click="publish">发 表</el-button>
    </div>
    <!--文本编辑器-->
    <div style="position: relative;border: 1px solid #d2d0d0;border-radius: 5px;height: 160px;margin:10px;box-sizing: border-box;padding: 10px">
      <div id="editor" style="max-height: 100px;overflow: auto"></div>
      <i @click="showEmoji" @click.stop class="iconfont icon-expression" style="position: absolute;right: 20px;bottom: 13px;cursor:pointer;"></i>
      <emoji v-if="emojiVisible" style="position: absolute;right: 10px;transform: translateY(20%);z-index: 4" @select="selectEmoji"></emoji>
    </div>
    <div>
    <!--文本编辑器-->
      <div style="display: flex;flex-wrap: wrap">
        <!--  照片朋友圈开始-->
        <picture-item v-for="(url, i) in imgUrlArr" :src="url" :index="i" :key="i" @getUrl="deleteImg" style="margin: 11px;"></picture-item>
        <!--  照片朋友圈结束-->
        <!-- 视频朋友圈开始-->
        <div v-if="videoUrl" style="position: relative;width: 400px;margin: 20px auto;">
          <video :src="videoUrl" controls style="display: block;width: 400px"></video>
          <div class="el-icon-close" style="position: absolute;right: 0;top: 0;transform: translate(50%, -50%);color: rgb(195 191 191);
        font-size: 20px;cursor: pointer;z-index: 20" title="删除" @click="deleteVideo"></div>
        </div>
        <!--  视频朋友圈结束-->
        <div v-if="uploadVisible" style="width: 160px;height: 160px;line-height: 160px;margin: 11px;background-color: #f7f7f7;
        font-size: 40px;color: #6d6d6d;text-align: center;border-radius: 5px;">
          <i class="el-icon-plus" style="cursor: pointer" @click="selectFile"></i>
        </div>
      </div>
      <input ref="fileInput" type="file" accept=".jpg,.jpeg,.mp4,.png" multiple style="display: none" @change="handleSelectFile">
    </div>
  </div>
</template>
<script>
import PictureItem from './PictureItem.vue'
import Emoji from './Emoji'
import Quill from 'quill'
export default {
  data: function () {
    return {
      imgUrlArr: [],
      videoUrl: null,
      content: '',
      quill: null,
      emojiVisible: false
    }
  },
  mounted () {
    this.quill = new Quill('#editor', {
      theme: 'snow',
      placeholder: '这一刻的想法',
      modules: {
        toolbar: []
      }})
    this.quill.focus()
  },
  methods: {
    deleteVideo () {
      this.deleteFile(this.videoUrl)
      this.videoUrl = null
    },
    // 组件传回的url,和数组下标index
    deleteImg (url, index) {
      this.deleteFile(url)
      this.imgUrlArr.splice(index, 1)
    },
    // 选择照片或视频
    selectFile () {
      // 重置value，多次选择同一文件才可触发
      this.$refs.fileInput.value = null
      this.$refs.fileInput.click()
    },
    async handleSelectFile (event) {
      let files = event.target.files
      for (let i = 0; i < files.length; i++) {
        let fileExtension = files[i].name.split('.').pop()
        // 视频
        if (fileExtension === 'mp4' && i === 0) {
          // 清空照片数组
          this.imgUrlArr = []
          // 获取url
          let url = await this.uploadFile(files[0])
          this.videoUrl = url
          break
        } else if (fileExtension === 'jpeg' || fileExtension === 'jpg' || fileExtension === 'png') {
          // 清空视频
          this.videoUrl = null
          // 获取url
          let url = await this.uploadFile(files[i])
          this.imgUrlArr.push(url)
          // 照片数量最多9张
          if (this.imgUrlArr.length === 9) {
            break
          }
        }
      }
    },
    // 发表朋友圈
    publish () {
      let type
      let mediaUrls = []
      if (this.videoUrl !== null) {
        type = 1
        mediaUrls.push(this.videoUrl)
      } else {
        type = 0
        mediaUrls = this.imgUrlArr
      }

      let userId = this.$store.state.currentUser.id
      this.content = this.quill.root.innerHTML
      if (this.content === '<p><br></p>') {
        this.content = ''
      }
      console.log('this.content = ' + this.content)
      let textContent = this.content
      let moment = {userId, textContent, type, mediaUrls}

      this.axios.post('/api/v1/moment/publish', moment).then((response) => {
        if (response.data.code === 1) {
          this.$message.success('发表成功!')
          this.$router.push('/home/moment/main')
        } else {
          this.$message.error('发表失败!')
        }
      })
    },
    // 根据url删除文件
    deleteFile (url) {
      const formData = new FormData()
      formData.append('fileName', url)
      this.axios.post('/api/v1/file/delete', formData, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      }).then((response) => {
        if (response.data.code === 1) {
          this.$message.success('删除成功!')
        } else {
          this.$message.error('删除失败!')
          console.log('deleteFile data = ' + response.data.message)
        }
      })
    },
    // 上传照片或视频,获取url
    async uploadFile (file) {
      const loading = this.$loading({
        target: '.moment-publish',
        text: '上传文件中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const formData = new FormData()
        formData.append('file', file)
        const response = await this.axios.post('/api/v1/file/upload/moment', formData, {
          headers: {
            'Content-type': 'multipart/form-data'
          }
        })

        loading.close()

        if (response.data.code === 1) {
          let url = response.data.data
          return url
        } else {
          this.$message.error('文件上传失败!')
          return null
        }
      } catch (error) {
        loading.close()
        this.$message.info('服务器繁忙!')

        console.log('error ' + error)
      }
    },
    navigate (path) {
      this.$router.push(path)
    },
    showEmoji () {
      this.emojiVisible = !this.emojiVisible
    },
    hideEmoji () {
      this.emojiVisible = false
    },
    selectEmoji (url) {
      this.emojiVisible = false
      const range = this.quill.getSelection(true)
      // 插入表情包
      this.quill.insertEmbed(range.index, 'image', url)
      this.content = this.quill.root.innerHTML
      // 将光标移到最后
      this.quill.setSelection(range.index + 1, 0)
    }
  },
  computed: {
    uploadVisible () {
      if (this.videoUrl === null && this.imgUrlArr.length === 0) { // 视频和图片都没选择
        return true
      } else if (this.videoUrl === null && this.imgUrlArr.length !== 9) { // 选择图片
        return true
      }

      return false
    }
  },
  components: {
    PictureItem,
    Emoji
  }
}
</script>
<style>
.moment-publish {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 50%;
  width: 550px;
  transform: translateX(-50%);
  overflow: auto;
  border-left: 1px solid #b8b7b7;
  border-right: 1px solid #b8b7b7;
}
.moment-publish::-webkit-scrollbar{
  display: none;
}
#textarea{
  width: 100%;
  height: 100px;
  padding: 20px;
  box-sizing: border-box;
  border: none;
}
#textarea:focus{
  outline: none;
}
</style>
